import json

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

#http://www.sahajamit.com/post/capturing-websocket-messages-using-selenium/
#https://stackoverflow.com/questions/27644615/getting-chrome-performance-and-tracing-logs

def create_driver():
  caps = DesiredCapabilities.CHROME
  caps['loggingPrefs'] = { 'performance':'ALL' }
  driver = webdriver.Chrome('chromedriver', desired_capabilities=caps)
  driver.implicitly_wait(3)
  driver.get('https://upbit.com')
  driver.implicitly_wait(8)
  driver.get("https://upbit.com/exchange?code=CRIX.UPBIT.KRW-BTC")
  return(driver)

def create_driver2():
  driver = webdriver.Chrome('chromedriver')
  driver.implicitly_wait(3)
  driver.get('https://upbit.com')
  driver.implicitly_wait(8)
  # signup by hand
  driver.get('https://upbit.com/signin')
  return(driver)

def strip_left(line, prefix):
  if line.startswith(prefix):
    return line[len(prefix):]
  else:
    return line

def gen_websocket_received(driver):
  for entry in driver.get_log("performance"):
    message_str = entry['message']
    message = json.loads(message_str)
    timestamp = message['message']["params"]["timestamp"]
    method = message['message']["method"]
    if method.lower() == "Network.webSocketFrameReceived".lower():
      payload_str = message['message']['params']['response']['payloadData']
      if payload_str.startswith("a"):
        payload_str = strip_left(payload_str, "a")
        payload = json.loads(payload_str)
        for payload_elem_str in payload:
          payload_elem = json.loads(payload_elem_str)
          yield payload_elem
      elif payload_str.startswith("h"):
        pass
      else:
        pass

driver = create_driver()

while True:
  for entry in gen_websocket_received(driver):
    type = entry["type"]
    if type == "crixOrderbook":
      print("book", entry)
    elif type == "crixTrade":
      print("trade", entry)
    else:
      pass

import jwt
encoded = jwt.encode({'access_key': accessKey, "nonce": 1515839513940}, secretKey, algorithm='HS256')

$.ajax({
  url: "https://ccx.upbit.com/api/v1/orders",
  type: "post",
  data: {
    market:"KRW-TIX",
    ord_type:"limit",
    price:1500,
    side:"bid",
    volume:35
  },
  headers: {
    Authorization:"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhY2Nlc3Nfa2V5IjoiOFl4SE9uYjZJcWRVSkpzVU9FSzN5VDRnQ3pkSmVNZ28yYUtGeFRWOCIsIm5vbmNlIjoxNTE1ODM5NTEzOTQwfQ._Ue9yYL2AEq6zI3Z1xyv0YqOGsrt-MOPkwsc86CO3Y8"
  },
  dataType: "json"
})

$.ajax({
  url: "https://ccx.upbit.com/api/v1/orders",
  type: "get",
  headers: {
    Authorization:"Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhY2Nlc3Nfa2V5IjoiOFl4SE9uYjZJcWRVSkpzVU9FSzN5VDRnQ3pkSmVNZ28yYUtGeFRWOCIsIm5vbmNlIjoxNTE1ODM5NTEzOTQyfQ.iWOKnCR0VYt7TxsShPNJ9lt-9AgyUptEpOxjjnp53uw"
  },
})

request_payload = {ord_type: "limit", market: "KRW-XRP", side: "bid", volume: 500, price: 100}
response = {"uuid":"4ae34a21-21ad-4139-9391-bda5562b75a9","side":"bid","ord_type":"limit","price":"100.0","avg_price":"0.0","state":"wait","market":"KRW-XRP","created_at":"2018-01-09T11:31:05+09:00","volume":"500.0","remaining_volume":"500.0","reserved_fee":"25.0","remaining_fee":"25.0","paid_fee":"0.0","locked":"50025.0","executed_volume":"0.0","trades_count":0}
